<template>
    <!--  dialogShow绑定对话框是否展示，默认为false-->
    <el-dialog :visible.sync="dialogShow" :title="dialogTitle" :close-on-click-modal="false" append-to-body top="5vh"
               width="900px" height="400px">
        <!-- 大盒子-->
        <div class="app-container">
            <!--   element ui   -->
            <el-form ref="form" :model="form" label-width="110px">
                <!-- 检索框-->
                <el-form-item label="详细地址：" prop="address">
                    <el-autocomplete
                            v-model="form.address"
                            style="width: 700px"
                            popper-class="autoAddressClass"
                            :fetch-suggestions="querySearchAsync"
                            :trigger-on-focus="false"
                            placeholder="详细地址"
                            clearable
                            @select="handleSelect"
                    >
                        <template slot-scope="{ item }">
                            <i class="el-icon-search fl mgr10"/>
                            <div style="overflow: hidden">
                                <div class="title">{{ item.title }}</div>
                                <span class="address ellipsis">{{ item.address }}</span>
                            </div>
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <!-- 地图的盒子-->
                <el-form-item label="地图定位：">
                    <div id="map-container" style="width: 700px; height: 350px"/>
                </el-form-item>
                <!-- 按钮事件-->
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                    <el-button @click="handleClose">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </el-dialog>
</template>

<script>
    /* 无须在引入，因为在父组件已经引入了 */
    //import loadBMap from "@/utils/loadBMap.js";

    export default {
        data() {
            return {
                dialogShow: false,//对话框状态
                dialogTitle: '地图定位',
                form: {
                    address: "", // 详细地址
                    addrPoint: {
                        // 详细地址经纬度
                        lng: 0,
                        lat: 0,
                    },
                },
                map: "", // 地图实例
                mk: "", // Marker实例
                locationPoint: null,
            };
        },

        methods: {
            //必须使用$nextTick不然第一次地图会初始化失败，第二次才看得地图
            // 必须使用$nextTick不然地图的创建坐标会比地图挂载还快。第一次会初始化失败
            myMehod() {
                //将对话框状态改为true，也就是打开对话框
                this.dialogShow = true
                this.$nextTick(() => {
                    this.initMap()
                })
            },
            // 初始化地图
            initMap() {
                console.log("123")
                var that = this;
                // 1、挂载地图
                this.map = new BMap.Map("map-container", {enableMapClick: false});
                var point = new BMap.Point(119.30244559059787, 26.106339983665546);//默认点位
                this.map.centerAndZoom(point, 19);

                // 3、设置图像标注并绑定拖拽标注结束后事件
                this.mk = new BMap.Marker(point, {enableDragging: true});
                this.map.addOverlay(this.mk);
                this.mk.addEventListener("dragend", function (e) {
                    that.getAddrByPoint(e.point);
                });

                // 4、添加（右上角）平移缩放控件
                this.map.addControl(
                    new BMap.NavigationControl({
                        anchor: BMAP_ANCHOR_TOP_RIGHT,
                        type: BMAP_NAVIGATION_CONTROL_SMALL,
                    })
                );

                // 5、添加（左下角）定位控件
                // var geolocationControl = new BMap.GeolocationControl({
                //     anchor: BMAP_ANCHOR_BOTTOM_LEFT,
                // });
                // geolocationControl.addEventListener("locationSuccess", function (e) {
                //     that.getAddrByPoint(e.point);
                // });
                // geolocationControl.addEventListener("locationError", function (e) {
                //     //alert(e.message);
                //     console.log("locationError", e.message)
                // });
                // this.map.addControl(geolocationControl);

                // 6、浏览器定位
                this.geolocation();

                // 7、绑定点击地图任意点事件
                this.map.addEventListener("click", function (e) {
                    that.getAddrByPoint(e.point);
                });
            },
            // 获取两点间的距离
            getDistancs(pointA, pointB) {
                return this.map.getDistance(pointA, pointB).toFixed(2);
            },
            // 浏览器定位函数
            geolocation() {
                var that = this;
                var geolocation = new BMap.Geolocation();
                geolocation.getCurrentPosition(
                    function (res) {
                        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                            that.getAddrByPoint(res.point);
                            that.locationPoint = res.point;
                        } else {
                            //alert("failed" + this.getStatus());
                            console.log("failed", this.getStatus())
                            that.locationPoint = new BMap.Point(119.30244559059787, 26.106339983665546);
                        }
                    },
                    {enableHighAccuracy: true}
                );
            },
            // 2、逆地址解析函数
            getAddrByPoint(point) {
                var that = this;
                var geco = new BMap.Geocoder();
                // geco.getLocation(point, function (res) {
                //     //console.log(res);
                //     that.mk.setPosition(point);
                //     that.map.panTo(point);
                //     // that.form.address = res.address;
                //     // that.form.addrPoint = point;
                // });
            },
            // 8-1、地址搜索
            querySearchAsync(str, cb) {
                var options = {
                    onSearchComplete: function (res) {
                        var s = [];
                        if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                            for (var i = 0; i < res.getCurrentNumPois(); i++) {
                                s.push(res.getPoi(i));
                            }
                            cb(s);
                        } else {
                            cb(s);
                        }
                    },
                };
                var local = new BMap.LocalSearch(this.map, options);
                local.search(str);
            },
            // 8-2、选择地址
            handleSelect(item) {
                this.form.address = item.address + item.title;
                this.form.addrPoint = item.point;
                this.map.clearOverlays();
                this.mk = new BMap.Marker(item.point);
                this.map.addOverlay(this.mk);
                this.map.panTo(item.point);
            },
            //提交数据
            onSubmit() {
                // console.log('纬度:',this.form.addrPoint.lat);
                // console.log('经度:',this.form.addrPoint.lng);
                //传输数据
                this.$emit('afterSelectPosition', this.form)//子组件向父组件通信
                //提示框
                this.$confirm('地址确定好了吗, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //将对话框状态改为false，也就是关闭对话框
                    this.dialogShow = false
                    //将文本域数据清空，不然第二次进来会有数据
                    this.form.address = ''
                })

            },
            handleClose() {
                //将对话框状态改为false，也就是关闭对话框
                this.dialogShow = false
                //提示
                this.$message({
                    type: 'success',
                    message: "关闭地图"
                })
                //将文本域数据清空，不然第二次进来会有数据
                this.form.address = ''
            }
        },
    };
</script>

<style  scoped>
    .autoAddressClass li {
        i.el-icon-search {
            margin-top: 11px;
        }

        .mgr10 {
            margin-right: 10px;
        }

        .title {
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .address {
            line-height: 1;
            font-size: 12px;
            color: #b4b4b4;
            margin-bottom: 5px;
        }
    }
</style>

